package com.hengxinguotong.zhihuichengjian.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AddGroupAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AddGroupTopAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectGroupPop;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.logger.Logger;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 老版本添加班组 目前没有使用
 * Created by liux on 2017/3/2.
 */

public class AddGroupActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_group)
    HXTextView saveGroup;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.profession_iv)
    ImageView professionIv;
    @BindView(R.id.profession_ll)
    LinearLayout professionLl;
    @BindView(R.id.position_iv)
    ImageView positionIv;
    @BindView(R.id.position_ll)
    LinearLayout positionLl;
    @BindView(R.id.seniority_iv)
    ImageView seniorityIv;
    @BindView(R.id.seniority_ll)
    LinearLayout seniorityLl;
    @BindView(R.id.top_recyclerview)
    RecyclerView topRecyclerview;
    @BindView(R.id.personnel_lv)
    PullToRefreshListView personnelLv;
    @BindView(R.id.group_name_ev)
    HXEditTextView groupNameEv;
    @BindView(R.id.select_ll)
    LinearLayout selectLl;
    @BindView(R.id.profession_tv)
    HXTextView professionTv;
    @BindView(R.id.position_tv)
    HXTextView positionTv;
    @BindView(R.id.seniority_tv)
    HXTextView seniorityTv;
    @BindView(R.id.title_tv)
    HXTextView titleTv;

    private AddGroupAdapter addGroupAdapter;
    private AddGroupTopAdapter addGroupTopAdapter;
    private int pageIndex = 1;
    private List<User> mUsers;
    public static final int ADDTYPE = 1;
    public static final int EDITTYPE = 2;
    private int type = 1;
    private String teamId;
    private String teamName;
    private SelectGroupPop mSelectGroupPop;

    private String positionndex;
    private String professionIndex;
    private String ageString;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addgroup);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", ADDTYPE);
        if (type == EDITTYPE) {
            titleTv.setText("添加人员");
            groupNameEv.setEnabled(false);
            teamId = getIntent().getStringExtra("teamId");
            teamName = getIntent().getStringExtra("teamName");
            groupNameEv.setText(teamName);
        }
        addListener();
        personnelLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        getPersonnelList(getResources().getString(R.string.loading));
    }


    private void initRecyclerView() {
        addGroupTopAdapter = new AddGroupTopAdapter(this, addGroupAdapter.getSelects());
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        topRecyclerview.setLayoutManager(linearLayoutManager1);
        topRecyclerview.setAdapter(addGroupTopAdapter);
    }

    private void addListener() {
        personnelLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                User userInfo = (User) addGroupAdapter.getItem(position - 1);
                if (addGroupAdapter.getSelects().contains(userInfo)) {
                    addGroupAdapter.getSelects().remove(userInfo);
                } else {
                    addGroupAdapter.getSelects().add(userInfo);
                }
                addGroupAdapter.notifyDataSetChanged();
                addGroupTopAdapter.notifyDataSetChanged();

            }
        });

        personnelLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getPersonnelList(null);
            }
        });
    }


    private void getPersonnelList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("title", positionndex);
            jsonObject.put("workType", professionIndex);
            jsonObject.put("workAge", ageString);
            jsonObject.put("type", "1");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/team/queryPersonList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes personnelListRes = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    addData(personnelListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
            }
        });
    }


    private void addData(List<User> datas) {
        if (pageIndex == 1) {
            mUsers = datas;
            addGroupAdapter = new AddGroupAdapter(mUsers, this);
            personnelLv.setAdapter(addGroupAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                personnelLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            }
            initRecyclerView();
        } else {
            mUsers.addAll(datas);
            addGroupAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            personnelLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }


    @OnClick({R.id.iv_back, R.id.save_group, R.id.profession_ll, R.id.position_ll, R.id.seniority_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_group:
                addGroup();
                break;
            case R.id.profession_ll:
                showSelectPop(Constants.professionString, 1);
                break;
            case R.id.position_ll:
                showSelectPop(Constants.positionString, 2);
                break;
            case R.id.seniority_ll:
                showSelectPop(Constants.workAgeString, 3);
                break;
        }
    }


    private void showSelectPop(final String[] strings, final int type) {
        mSelectGroupPop = new SelectGroupPop(this, strings, new SelectGroupPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                switch (type) {
                    case 1:
                        if (position == strings.length - 1) {
                            professionIndex = "";
                            professionTv.setText("工种");
                        } else {
                            professionIndex = position + 1 + "";
                            professionTv.setText(strings[position]);
                        }

                        pageIndex = 1;
                        getPersonnelList(getResources().getString(R.string.loading));
                        break;
                    case 2:
                        if (position == strings.length - 1) {
                            positionndex = "";
                            positionTv.setText("职称");
                        } else {
                            positionndex = position + 1 + "";
                            positionTv.setText(strings[position]);

                        }
                        pageIndex = 1;
                        getPersonnelList(getResources().getString(R.string.loading));
                        break;
                    case 3:
                        if (position == strings.length - 1) {
                            ageString = "";
                            seniorityTv.setText("工龄");
                        } else {
                            ageString = position + 1 + "";
                            seniorityTv.setText(strings[position]);

                        }
                        pageIndex = 1;
                        getPersonnelList(getResources().getString(R.string.loading));
                        break;

                }

            }
        });
        mSelectGroupPop.setFocusable(true);
        mSelectGroupPop.setOutsideTouchable(true);
        mSelectGroupPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectGroupPop.update();
        mSelectGroupPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectGroupPop.isShowing()) {
            mSelectGroupPop.dismiss();
        } else {
            mSelectGroupPop.showAsDropDown(selectLl);
        }
    }


    private void addGroup() {
        if (addGroupAdapter == null) {
            return;
        }

        List<User> selects = addGroupAdapter.getSelects();
        if (selects.size() == 0) {
            showToast("请添加人员");
            return;
        }

        if (Utils.isEmpty(groupNameEv.getEditableText().toString())) {
            showToast("请填写群组名称");
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < selects.size(); i++) {
            User user = selects.get(i);
            if (i == selects.size() - 1) {
                stringBuilder.append(user.getPersonId());
            } else {
                stringBuilder.append(user.getPersonId() + ",");
            }
        }

        Logger.d("stringBuilder----------" + stringBuilder.toString());

        JSONObject jsonObject = new JSONObject();
        try {
            if (type == EDITTYPE) {
                jsonObject.put("teamId", teamId);
                jsonObject.put("personId", stringBuilder.toString());
            } else {
                jsonObject.put("name", groupNameEv.getEditableText().toString());
                jsonObject.put("personId", stringBuilder.toString());
            }
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), this, "/team/addTeam/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }
}
